package cn.net.mugui.net.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import com.mugui.base.base.Autowired;
import com.mugui.base.base.Component;
import com.mugui.base.util.Other;

import cn.net.mugui.net.key.utils.Base58;
import cn.net.mugui.net.udp.UdpBaseServer.ReceiveListener;

/**
 * 接收方的通用处理器
 *
 * @author 木鬼
 */
@Component
public class UdpReceiveListener implements ReceiveListener {

    @Autowired
    private UdpBaseServer udpBaseServer;

    @Autowired
    private UdpServerManager udpServerManager;

    /**
     * 通用的包接收处理器
     * @param socket 
     */
    @Override
    public void receive(DatagramSocket socket, DatagramPacket server) {

        byte[] data = server.getData();
        byte[] length = new byte[4];
        System.arraycopy(data, 0, length, 0, 4);
        int byteArrayint = Other.byteArrayint(length);
        byte[] bag_data = new byte[byteArrayint];
        System.arraycopy(data, 4, bag_data, 0, byteArrayint);

        UdpBag resolve = UdpBag.resolve(bag_data);
       if(!checkUdpBag(resolve)) {
    	   
    	   return;
       }
        UdpServer udpServer = udpServerManager.get(Base58.encode(resolve.getFrom()), server.getAddress().getHostAddress(),
                server.getPort());
        try { 
            udpServer.receive(socket,resolve);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	private boolean checkUdpBag(UdpBag resolve) {
		 if(resolve.getBag_type()!=0&&resolve.getBag_type()!=1) {
	        	return false;
	        }
		 if(resolve.getFrom()==null||resolve.getTo()==null) {
			 return false;
		 }
		return true;
	}

}
